<?php

namespace Biz\model\redPacket;

use Doraemon\pockets\datebase\BaseDbModel;

class RedPacketsLog extends BaseDbModel
{

    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_redpacket';

    const _DATABASE_ = 'biz_red_packet';

    const _TABLE_NAME = 'red_packets_log';

    const TYPE_INCOME = 1;//收入
    const TYPE_PAY = 2;//支出
    const TYPE_REFUND = 3;//退还
    const TYPE_ADMIN_SEND = 4;//管理员发放（收入）

    const TYPE_DESC_MAP = [
        self::TYPE_INCOME => '收入',
        self::TYPE_PAY => '支出',
        self::TYPE_REFUND => '退还',
        self::TYPE_ADMIN_SEND => '收入',
    ];

    public static function getIncomeCount($uid, $startTime, $endTime)
    {
        $where = [
            'uid' => $uid,
            'type' => self::TYPE_INCOME,
            'addtime[>]' => $startTime,
            'addtime[<]' => $endTime
        ];
        return self::count('*', $where);
    }

    /**
     * 是否领过红包
     * @param $uid
     * @param $orderNo
     * @return mixed
     */
    public static function hasIncome($uid, $orderNo)
    {
        return self::has(['uid' => $uid, 'order_no' => $orderNo, 'type' => self::TYPE_INCOME]);
    }

    public static function getPayLog($uid, $orderNo)
    {
        return self::get('*', ['uid' => $uid, 'order_no' => $orderNo, 'type' => self::TYPE_PAY]);
    }

    /**
     * 是否使用过红包
     * @param $uid
     * @param $orderNo
     * @return mixed
     */
    public static function hasUse($uid, $orderNo)
    {
        return self::has(['uid' => $uid, 'order_no' => $orderNo, 'type' => self::TYPE_PAY]);
    }


    public static function addData($data)
    {
        $now = date('Y-m-d H:i:s');
        $data['addtime'] = $now;
        $data['edittime'] = $now;
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function updateData($data, $where)
    {
        $data['edittime'] = date('Y-m-d H:i:s');
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function getUserListAndCount($where)
    {
        $list = self::getUserList($where);
        $total = self::getUserCount($where);
        return compact('list', 'total');
    }

    public static function getUserList($where)
    {
        if (!isset($where['ORDER'])) {
            $where['ORDER'] = [
                'id' => 'DESC'
            ];
        }
        if (empty($where['AND'])) {
            unset($where['AND']);
        }
        $list = self::select("*", $where);
        return $list;
    }

    public static function getUserCount($where)
    {
        if (isset($where['LIMIT'])) {
            unset($where['LIMIT']);
        }
        if (isset($where['ORDER'])) {
            unset($where['ORDER']);
        }
        $rs = self::count('*', $where);
        return $rs;
    }
}

